#include "HistoryModel.h"
#include "services/DatabaseService.h"
#include "utils/Logger.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QDebug>

HistoryModel::HistoryModel(QObject *parent)
    : QSqlTableModel(parent, DatabaseService::instance()->database())
{
    // 设置表名
    setTable("realtime_data");

    // 设置编辑策略（手动提交）
    setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置排序（按时间戳降序）
    setSort(fieldIndex("timestamp"), Qt::DescendingOrder);

    // 设置表头显示名称
    setHeaderData(fieldIndex("id"), Qt::Horizontal, "ID");
    setHeaderData(fieldIndex("device_id"), Qt::Horizontal, "设备ID");
    setHeaderData(fieldIndex("timestamp"), Qt::Horizontal, "时间");
    setHeaderData(fieldIndex("temperature"), Qt::Horizontal, "温度(℃)");
    setHeaderData(fieldIndex("pressure"), Qt::Horizontal, "压力(kPa)");
    setHeaderData(fieldIndex("flow"), Qt::Horizontal, "流量(L/min)");
}

HistoryModel::~HistoryModel()
{
}

// 重写数据方法以自定义显示格式
QVariant HistoryModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    // 获取原始数据
    QVariant value = QSqlTableModel::data(index, role);

    // 对时间戳列进行格式化
    if (role == Qt::DisplayRole)
    {
        QString fieldName = this->record().fieldName(index.column());
        if (fieldName == "timestamp")
        {
            QDateTime dt = value.toDateTime();
            return dt.toString("yyyy-MM-dd HH:mm:ss");
        }
        else if (fieldName == "temperature" || fieldName == "pressure")
        {
            return QString::number(value.toDouble(), 'f', 1);
        }
        else if (fieldName == "flow")
        {
            return QString::number(value.toDouble(), 'f', 2);
        }
    }

    return value;
}

// 设置设备 ID 过滤
void HistoryModel::setDeviceId(const QString &deviceId)
{
    if (m_deviceId == deviceId)
        return;

    m_deviceId = deviceId;
    emit deviceIdChanged();

    qDebug() << "HistoryModel: 设置设备过滤:" << deviceId;
}

// 设置开始时间
void HistoryModel::setStartTime(const QDateTime &startTime)
{
    if (m_startTime == startTime)
        return;

    m_startTime = startTime;
    emit startTimeChanged();

    qDebug() << "HistoryModel: 设置开始时间:" << startTime.toString("yyyy-MM-dd HH:mm:ss");
}

// 设置结束时间
void HistoryModel::setEndTime(const QDateTime &endTime)
{
    if (m_endTime == endTime)
        return;

    m_endTime = endTime;
    emit endTimeChanged();

    qDebug() << "HistoryModel: 设置结束时间:" << endTime.toString("yyyy-MM-dd HH:mm:ss");
}

// 获取记录数量
int HistoryModel::recordCount() const
{
    return rowCount();
}

// 查询历史数据
bool HistoryModel::queryHistoryData()
{
    qInfo() << "HistoryModel: 查询历史数据";

    // 应用过滤器
    applyFilters();

    // 执行查询
    bool success = select();

    if (success)
    {
        int count = rowCount();
        qInfo() << "HistoryModel: 查询成功，共" << count << "条记录";
        emit recordCountChanged();
        emit queryCompleted(true, count);
    }
    else
    {
        qWarning() << "HistoryModel: 查询失败:" << lastError().text();
        emit queryCompleted(false, 0);
    }

    return success;
}

// 查询最近 N 小时的数据
bool HistoryModel::queryLastHours(const QString &deviceId, int hours)
{
    m_deviceId = deviceId;
    m_endTime = QDateTime::currentDateTime();
    m_startTime = m_endTime.addSecs(-hours * 3600);

    emit deviceIdChanged();
    emit startTimeChanged();
    emit endTimeChanged();

    qInfo() << "HistoryModel: 查询最近" << hours << "小时数据 - 设备:" << deviceId;
    return queryHistoryData();
}

// 查询最近 N 天的数据
bool HistoryModel::queryLastDays(const QString &deviceId, int days)
{
    m_deviceId = deviceId;
    m_endTime = QDateTime::currentDateTime();
    m_startTime = m_endTime.addDays(-days);

    emit deviceIdChanged();
    emit startTimeChanged();
    emit endTimeChanged();

    qInfo() << "HistoryModel: 查询最近" << days << "天数据 - 设备:" << deviceId;
    return queryHistoryData();
}

// 查询日期范围数据
bool HistoryModel::queryDateRange(const QString &deviceId, const QDateTime &start, const QDateTime &end)
{
    m_deviceId = deviceId;
    m_startTime = start;
    m_endTime = end;

    emit deviceIdChanged();
    emit startTimeChanged();
    emit endTimeChanged();

    qInfo() << "HistoryModel: 查询日期范围 -"
            << "设备:" << deviceId
            << "从" << start.toString("yyyy-MM-dd HH:mm:ss")
            << "到" << end.toString("yyyy-MM-dd HH:mm:ss");
    return queryHistoryData();
}

// 查询今天的数据
bool HistoryModel::queryToday(const QString &deviceId)
{
    m_deviceId = deviceId;

    QDateTime now = QDateTime::currentDateTime();
    m_startTime = QDateTime(now.date(), QTime(0, 0, 0));
    m_endTime = QDateTime(now.date(), QTime(23, 59, 59));

    emit deviceIdChanged();
    emit startTimeChanged();
    emit endTimeChanged();

    qInfo() << "HistoryModel: 查询今日数据 - 设备:" << deviceId;
    return queryHistoryData();
}

// 查询昨天的数据
bool HistoryModel::queryYesterday(const QString &deviceId)
{
    m_deviceId = deviceId;

    QDateTime now = QDateTime::currentDateTime();
    QDate yesterday = now.date().addDays(-1);
    m_startTime = QDateTime(yesterday, QTime(0, 0, 0));
    m_endTime = QDateTime(yesterday, QTime(23, 59, 59));

    emit deviceIdChanged();
    emit startTimeChanged();
    emit endTimeChanged();

    qInfo() << "HistoryModel: 查询昨日数据 - 设备:" << deviceId;
    return queryHistoryData();
}

// 获取平均温度
double HistoryModel::getAverageTemperature() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT AVG(temperature) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 获取平均压力
double HistoryModel::getAveragePressure() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT AVG(pressure) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 获取平均流量
double HistoryModel::getAverageFlow() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT AVG(flow) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 获取最大温度
double HistoryModel::getMaxTemperature() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT MAX(temperature) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 获取最大压力
double HistoryModel::getMaxPressure() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT MAX(pressure) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 获取最大流量
double HistoryModel::getMaxFlow() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT MAX(flow) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 获取最小温度
double HistoryModel::getMinTemperature() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT MIN(temperature) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 获取最小压力
double HistoryModel::getMinPressure() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT MIN(pressure) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 获取最小流量
double HistoryModel::getMinFlow() const
{
    QSqlQuery query(database());
    QString sql = QString("SELECT MIN(flow) FROM realtime_data WHERE %1")
                      .arg(buildWhereClause());

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toDouble();
    }

    return 0.0;
}

// 清空过滤条件
void HistoryModel::clearFilters()
{
    m_deviceId.clear();
    m_startTime = QDateTime();
    m_endTime = QDateTime();

    emit deviceIdChanged();
    emit startTimeChanged();
    emit endTimeChanged();

    // 清空过滤器
    setFilter("");

    qInfo() << "HistoryModel: 清空所有过滤条件";
}

// 刷新数据
void HistoryModel::refresh()
{
    qInfo() << "HistoryModel: 刷新数据";
    queryHistoryData();
}

// 构建 WHERE 子句
QString HistoryModel::buildWhereClause() const
{
    QStringList conditions;

    // 设备 ID 过滤
    if (!m_deviceId.isEmpty())
    {
        conditions.append(QString("device_id = '%1'").arg(m_deviceId));
    }

    // 开始时间过滤
    if (m_startTime.isValid())
    {
        conditions.append(QString("timestamp >= '%1'")
                              .arg(m_startTime.toString("yyyy-MM-dd HH:mm:ss")));
    }

    // 结束时间过滤
    if (m_endTime.isValid())
    {
        conditions.append(QString("timestamp <= '%1'")
                              .arg(m_endTime.toString("yyyy-MM-dd HH:mm:ss")));
    }

    // 如果没有条件，返回 "1=1"（始终为真）
    if (conditions.isEmpty())
    {
        return "1=1";
    }

    return conditions.join(" AND ");
}

// 应用过滤器
void HistoryModel::applyFilters()
{
    QString whereClause = buildWhereClause();
    setFilter(whereClause);

    qDebug() << "HistoryModel: 应用过滤条件:" << whereClause;
}
